package util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class KeywordUtil {
	public static Map<String, Integer> converge(Map<String, Integer> frequency,Map<String, Integer> oldFrequency) {
		Map<String, Integer> newFrequency = new HashMap<String, Integer>();
		Iterator<String> it1 = frequency.keySet().iterator();
		while(it1.hasNext()){
			String key = it1.next();
			if(oldFrequency.containsKey(key))
				newFrequency.put(key, frequency.get(key) + oldFrequency.get(key));
			else
				newFrequency.put(key, frequency.get(key));
		}
		Iterator<String> it2 = oldFrequency.keySet().iterator();
		while(it2.hasNext()){
			String key = it2.next();
			if(!newFrequency.containsKey(key))
				newFrequency.put(key, oldFrequency.get(key));
		}
		return newFrequency;
	}
	
	public static ArrayList<String> getTopKeywords(int num, final Map<String, Integer> frequency) throws Exception{
		ArrayList<String> keywords = new ArrayList<String>();
		ArrayList<String> keys = new ArrayList<String>(frequency.keySet());
		Collections.sort(keys, new Comparator<String>() {
			public int compare(String s1, String s2) {
				if (frequency.get(s1) < frequency.get(s2))
					return 1;

				else if (frequency.get(s1) == frequency.get(s2))
					return 0;
				else
					return -1;
			}
		});
		for(int i = 0; i < num && i < keys.size(); i++){
			keywords.add(keys.get(i));
		}
		return keywords;
	}
}
